package com.pangu.web.service.impl;

import com.pangu.web.handler.admin.shiro.ShiroUtils;
import com.pangu.web.handler.admin.user.SysRoleEntity;
import com.pangu.web.handler.admin.user.SysUserEntity;
import com.pangu.web.handler.admin.utils.IPUtils;
import com.pangu.web.service.SysUserService;
import com.pangu.web.service.repository.jpa.SysUserRepository;
import org.apache.commons.lang.RandomStringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

/**
 * @author Chris
 * @date 2018/4/23 12:48
 * @todo
*/
@Service
public class SysUserServiceImpl implements SysUserService {

    @Autowired
    private SysUserRepository sysUserRepository;

    @Override
    @Transactional
    public void saveSysUser(SysUserEntity sysUserEntity, javax.servlet.http.HttpServletRequest request) {
        sysUserEntity.setCreateTime(new Date());
        //sha256加密
        String salt = RandomStringUtils.randomAlphanumeric(20);
        sysUserEntity.setSalt(salt);
        sysUserEntity.setPassword(ShiroUtils.sha256(sysUserEntity.getPassword(), sysUserEntity.getSalt()));
        sysUserEntity.setLastLoginIp(IPUtils.getIpAddr(request));
        sysUserEntity.setLastLoginTime(new Date());
        sysUserEntity.setStatus(1);

        Set<SysRoleEntity> set=new HashSet<SysRoleEntity>();
        for (Long roleId:sysUserEntity.getRoleIdList()){
            set.add(SysRoleEntity.of().setRoleId(roleId));
        }
        sysUserEntity.setSysRoleEntities(set);
        sysUserRepository.save(sysUserEntity);

    }

}
